package com.greejoy.score.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.greejoy.score.MyApplication;
import com.greejoy.score.R;
import com.greejoy.score.domain.Judge;
import com.greejoy.score.domain.MatchInfo;
import com.greejoy.score.domain.MatchInfoBody;
import com.greejoy.score.service.HttpService;

import java.util.List;

import okhttp3.ResponseBody;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private long exitTime = 0;

    private MyApplication app;
    private Retrofit retrofit;
    private HttpService httpService;

    private TextView tv_match_name;
    private TextView tv_match_time;
    private TextView tv_ip;
    private TextView tv_match_address;

    private GridLayout gl_judge;
    private boolean goingScoreActivity = false;

    private GifImageView giv_ws_loading;

    private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(getString(R.string.broadcast_action))){
                String msg = intent.getStringExtra("msg");
                switch (msg){
                    case "showWsLoading":
                        giv_ws_loading.setVisibility(View.VISIBLE);
                        break;
                    case "hideWsLoading":
                        giv_ws_loading.setVisibility(View.INVISIBLE);
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getString(R.string.broadcast_action));
        registerReceiver(myBroadcastReceiver, intentFilter);

        app = MyApplication.getInstance();
        String httpUrl = app.dataMap.get("httpUrl");
        retrofit = new Retrofit.Builder().baseUrl(httpUrl).build();
        httpService = retrofit.create(HttpService.class);

        tv_match_name = findViewById(R.id.tv_match_name);
        tv_match_time = findViewById(R.id.tv_match_time);
        tv_match_address = findViewById(R.id.tv_match_address);
        tv_ip = findViewById(R.id.tv_ip);
        gl_judge = findViewById(R.id.gl_judge);

        findViewById(R.id.btn_download).setOnClickListener(this);
        findViewById(R.id.btn_setting).setOnClickListener(this);

        findViewById(R.id.btn_send_score).setOnClickListener(this);


        giv_ws_loading = findViewById(R.id.giv_ws_loading);

        refreshIp();

        refreshContent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        goingScoreActivity = false;
        app.dataMap.put("judgeId", null);
        app.dataMap.put("judgeName", null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_setting){
            Intent intent = new Intent(MainActivity.this, SettingActivity.class);
            startActivity(intent);
            finish();
        }else if(v.getId() == R.id.btn_download){
            String httpUrl = app.dataMap.get("httpUrl");
            String url = httpUrl + "/apk/app.apk";
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
        }else if(v.getId() == R.id.btn_send_score){
            Intent intent = new Intent(MainActivity.this, WebViewActivityV.class);
            String httpUrl = app.dataMap.get("httpUrl");
            String url = httpUrl + "/js/app/sendScore?key=" + getString(R.string.server_key);
            intent.putExtra("url", url);
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 1000) {
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            //彻底关闭整个APP
            Intent startMain = new Intent(Intent.ACTION_MAIN);
            startMain.addCategory(Intent.CATEGORY_HOME);
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(startMain);
            System.exit(0);
        }
    }

    private void refreshIp(){
        // 获取设备ip地址
        WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
        tv_ip = findViewById(R.id.tv_ip);
        tv_ip.setText(ip);
        app.dataMap.put("ip", ip);
    }

    private void refreshContent(){
        Call<ResponseBody> call = httpService.getMatchInfo(getString(R.string.server_key));
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()){

                    try {
                        String bodyStr = response.body().string();
                        MatchInfoBody matchInfoBody = JSON.parseObject(bodyStr, MatchInfoBody.class);
                        MatchInfo matchInfo = matchInfoBody.getData();
                        tv_match_name.setText(matchInfo.getName());
                        tv_match_time.setText(matchInfo.getTime());
                        tv_match_address.setText(matchInfo.getAddress());

                        List<Judge> judgeList = matchInfo.getJudgeList();
                        if(judgeList != null){
                            for (int i = 0; i < judgeList.size(); i++) {
                                Judge judge = judgeList.get(i);
                                Button button = new Button(MainActivity.this);
                                button.setText(judge.getName());
                                button.setOnClickListener(v -> {
                                    if(!goingScoreActivity){
                                        goingScoreActivity = true;
                                        Long judgeId = judge.getId();
                                        String judgeName = judge.getName();
                                        app.dataMap.put("judgeId", judgeId.toString());
                                        app.dataMap.put("judgeName", judgeName);
                                        finish();
                                        Intent intent = new Intent(MainActivity.this, WaitingActivity.class);
                                        intent.putExtra("judge_id", judgeId);
                                        intent.putExtra("judge_name", judgeName);
                                        startActivity(intent);
                                    }
                                });
                                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                                params.columnSpec = GridLayout.spec(i % 5, 1f);
                                gl_judge.addView(button, params);
                            }
                        }

                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();;
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

}